var api = require('../../../utils/api.js');
var util = require('../../../utils/util.js');
var md = require('../../../utils/md5.js');

var app = getApp();

Page({

  data: {
    cursor: true,
    focus: false,
    opacity: 1,
    shopname: '',
    limit: 100,
    page: 1,
    maskLayer: true,
    details: {},
    modifyPriceCol: true,
    groupBuyModifyPriceCol: true,
    preferentialPrice: 0,
    share: 1,
    send_to_customers:0,  //是否推送
    authorize: true, //授权
    helpCol: true
  },

  onLoad: function (options) {
    
    wx.hideShareMenu() // 隐藏分享按钮
    
    var that = this;
    wx.getUserInfo({
      success: function (res) {
        that.setData({
          userInfo: res.userInfo
        })
      }
    })

    if (options.inn_id) {
      this.setData({
        inn_id: options.inn_id
      })
    }
    // if (options.account_type){
    //   this.setData({
    //     account_type: options.account_type
    //   })
    // }
  },

  onShow: function () {
    this.storeDetail();
    this.shopReport();
    this.userStatus();
  },

  //获取个人状态详情
  userStatus: function (e) {
    var that = this;
    api.POST({
      params: "",
      url: app.globalData.base_url + 'user/status',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            account_type: res.data.data.account_type
          })
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },


  modify: function () {
    if (this.data.account_type == 2) {
      return false
    }
    this.setData({
      cursor: false,
      focus: true,
      opacity: 0
    })
  },
  lostFocus: function (e) {
    var shopname = e.detail.value
    var that = this;
    if (shopname) {
      if (shopname.length>8){
        shopname = shopname.slice(0,8)
      }
      this.setData({
        cursor: true,
        focus: false,
        opacity: 1,
        shopname: shopname
      })
    } else {
      this.setData({
        cursor: true,
        focus: false,
        opacity: 1
      })
    }
    var params = {
      inn_name: this.data.shopname
    }
    api.POST({
      params: params,
      url: app.globalData.base_url + "inn/saveName",
      success: function (res) {
        if (util.isEmpty(res.data.code)) {

        } else {
          that.storeDetail();
          util.showError(res.data.message);
        }
      }
    })
  },

  //店铺详情
  storeDetail: function () {
    var that = this;
    var page = this.data.page;
    var params = {
      inn_id: this.data.inn_id,
      limit: this.data.limit,
      page: this.data.page
    }
    api.POST({
      params: params,
      url: app.globalData.base_url + "inn/getGoodsList",
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.search;
          var totalPage = paging.total_page;
          var resultList = res.data.data.goods_list;
          var inn_name = res.data.data.inn_info.inn_name;
          var inn_id = res.data.data.inn_info.inn_id;
          var avatar = res.data.data.inn_info.avatar;
          var nickname = res.data.data.inn_info.nickname

          if (page == 1) {
            var itemData = resultList;
          } else {
            var itemData = that.data.product.concat(resultList)
          }

          that.setData({
            total_page: totalPage,
            product: itemData,
            shopname: inn_name,
            inn_id: inn_id,
            avatar: avatar,
            nickname: nickname
          })

        } else {
          util.showError(res.data.message);
        }
      }
    })
  },

  //小店统计
  shopReport:function(){
    var that = this;
    var params = {}
    api.POST({
      params: params,
      url: app.globalData.base_url + "inn/report",
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            report: res.data.data
          })

        } else {
          util.showError(res.data.message);
        }
      }
    })

  },

//移除商品
  removeProduct:function(e){
    var that = this;
    var sku_code = e.target.dataset.sku_code
    wx.showModal({
      title: '提示',
      content: '是否确认移除？',
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: { sku_code: sku_code},
            url: app.globalData.base_url + 'inn/removeOne',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                that.onShow();
              } else {
                util.showError(res.data.message);
              }
            },
            fail: function (fail) {
              util.showError("请检查网络");
            }
          })
        }
      }
    })

  },
  //分享
  onShareAppMessage: function (res) {
    var that = this;
    var uid = wx.getStorageSync('accountInfo').uid;
    var inn_id = this.data.inn_id;
    var nickname = wx.getStorageSync('accountInfo').nickname;
    if (res.target.dataset.index || res.target.dataset.index==0){
      var index = res.target.dataset.index
      var prouct = this.data.product[index]
      var share_type = that.data.share_type;
      var group_buy_number = that.data.group_buy_number;
      if (!that.data.groupBuyModifyPriceCol){
        var url = '/agent/pages/groupOrder/groupOrder?share_id=' + that.data.group_share_id;
        var share_img = that.data.group_share_img;
      }else{
        var url = '/agent/pages/storeProductDetail/storeProductDetail?sku_code=' + prouct.sku_code + '&inn_id=' + inn_id;
        var share_img = prouct.share_img;
      }
      var title = nickname + '向你分享了' + prouct.gname
    } else if (res.target.dataset.inn_id){
      var url = '/agent/pages/storeGoodsList/storeGoodsList?inn_id=' + res.target.dataset.inn_id;
      var share_img = app.globalData.base_url + 'images/share_01.jpg'
      var title = nickname + '向你分享了ta的小店'
    }
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: title,
        path: url,
        imageUrl: share_img,
        success: function (res) {
          // 转发成功
        },
        fail: function (res) {
          // 转发失败
        }
      }
    }
  },


  addGoods:function(){
    wx.navigateTo({
      url: '/agent/pages/addGoods/addGoods?account_type=' + this.data.account_type
    })
  },

  //子账号管理
  accountManage:function(){
    wx.navigateTo({
      url: '/agent/pages/subAccount/subAccount'
    })
  },
  //销量排行
  salesRank: function () {
    wx.navigateTo({
      url: '/agent/pages/salesRank/salesRank'
    })
  },

  //今日收入
  incomeLink: function () {
    wx.navigateTo({
      url: '/center/pages/myIncome/myIncome?currentTab=1'
    })
  },

   //团购订单列表
   groupListLink: function () {
      wx.navigateTo({
         url: '/agent/pages/groupList/groupList'
      })
   },

  //客户列表
  customerLink:function(){
    wx.navigateTo({
      url: '/agent/pages/customer/customer'
    })
  },

  //帮助弹窗
  helpButton:function(){
    this.setData({
      helpCol:false
    })
  },
  //关闭帮助弹窗
  closeHelpCol: function () {
    this.setData({
      helpCol: true
    })
  },

  previewShop:function(){
    var inn_id = this.data.inn_id;
    wx.navigateTo({
      url: '/agent/pages/storeGoodsList/storeGoodsList?inn_id=' + inn_id
    })
  },

  //是否推送
  send_customers:function(){
    var send_to_customers = this.data.send_to_customers;
    if (send_to_customers==1){
      this.setData({
        send_to_customers:0
      })
    } else if (send_to_customers == 0){
      this.setData({
        send_to_customers: 1
      })
    }
  },


  //修改价格
  modifyPrice: function (res) {
    var index = res.target.dataset.index
    var product = this.data.product[index]
    if (product.original_price == product.bottom_price){
      util.showStatus('该商品无法改价')
      return false
    }
    this.setData({
      modifyPriceCol: false,
      share: 1,
      rawData: product,
      preferentialPrice:0,
      newPrice:'',
      index: index,
      group_buy_number:1
    })
  },
  closeModifyPrice: function () {
    this.setData({
      modifyPriceCol: true
    })
  },


  getNewPrice: function (e) {
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    var money = this.data.newPrice / 1;
    var original_price = this.data.rawData.original_price / 1
    var minprice = this.data.rawData.bottom_price / 1
    var preferentialPrice = this.data.preferentialPrice;
		var groupBuyTotalPrice=0;
    var group_buy_number = (this.data.group_buy_number > 0) ? this.data.group_buy_number / 1 : 1;
    if (reg.test(money)) {
      if (money != 0) {
        money = money.toFixed(2);
        groupBuyTotalPrice = (group_buy_number*money).toFixed(2);
        preferentialPrice = (group_buy_number*(original_price - money)).toFixed(2);
      } else {
        money = ''
				groupBuyTotalPrice = (group_buy_number * original_price).toFixed(2);
        preferentialPrice = 0;
      }
    } else {
      util.showStatus('请输入正确的价格');
      return false
    }
    this.setData({
      newPrice: money,
      preferentialPrice: preferentialPrice,
			groupBuyTotalPrice: groupBuyTotalPrice
    })
  },

  //确认修改价格
  submitModifyPrice: function () {
    var that = this;
    var params = new Object()
    var timer = setTimeout(function () {

      var newPrice = parseFloat(that.data.newPrice)
      var bottom_price = parseFloat(that.data.rawData.bottom_price)
      var original_price = parseFloat(that.data.rawData.original_price)

      if (isNaN(newPrice)) {
        newPrice = 0
      }
      if (newPrice == '') {
        params.price = that.data.rawData.current_price;
      } else {
        if (newPrice < bottom_price) {
          util.showStatus("价格不得低于" + bottom_price);
          that.setData({
            newPrice: '',
            preferentialPrice: 0
          })
          return false
        }
        if (newPrice > original_price) {
          that.setData({
            newPrice: '',
            preferentialPrice: 0
          })
          util.showStatus("价格不得高于" + original_price);
          return false
        }
        params.price = that.data.newPrice;
      }


      params.sku_code = that.data.rawData.sku_code;
      params.send_to_customers = that.data.send_to_customers;
      api.POST({
        params: params,
        url: app.globalData.base_url + 'inn/savePrice',
        success: function (res) {
          if (util.isEmpty(res.data.code)) {
            util.showStatus("修改成功")
            that.setData({
              share: 2
            })
            that.storeDetail();
            clearTimeout(timer);
          } else {
            util.showStatus(res.data.message)
          }

        },
        fail: function (fail) {
          util.showErrorPath("../../../", "获取失败，请检查网络");
        }
      })
    }, 300)
  },

  //分享价格输入
  priceInput: function (e) {
    var reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
    var money = e.detail.value;
    var original_price = this.data.rawData.original_price;
    if (money.length > original_price.length) {
      money = money.slice(0, money.length - 1)
    }
    if (!reg.test(money)) {
      money = money.slice(0, money.length - 1)
    }
    this.setData({
      share: 1,
      newPrice: money
    })
  },

  changeShopName:function(e){
    var name = e.detail.value;
    if (name.length>8) {
      name = name.slice(0, 8)
    }
    this.setData({
      shopname: name
    })
  },

  getImageInfo: function () {
    var that = this;
    var index = this.data.index;
    var img = this.data.product[index].share_img_qrcode
    wx.getImageInfo({
      src: img,
      success: function (res) {
        that.setData({
          share_qr_code: res.path
        })
        setTimeout(function () {
          that.saveImage()
        }, 500);
      }
    })
  },
  handler: function (e) {
    if (e.detail.authSetting["scope.writePhotosAlbum"]) {
      this.saveImage();
      this.setData({
        authorize: true
      })
    }
  },
  saveImage: function () {
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.share_qr_code,
      success(res) {
        util.showError('保存图片成功')
      },
      fail: function (fail) {
        if (fail.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
          that.setData({
            authorize: false
          })
        }
      }
    })
  },
  helpCol:function(){
    this.setData({
      helpCol:true
    })
  },
  // 阻止冒泡
  clickContent: function () {

  },

  //团购修改价格
  groupBuyModifyPrice: function (res) {
    var index = res.target.dataset.index
    var product = this.data.product[index]
   //  if (product.original_price == product.bottom_price) {
   //    util.showStatus('该商品无法改价')
   //    return false
   //  }
    this.setData({
      groupBuyModifyPriceCol: false,
      share: 1,
      rawData: product,
      preferentialPrice: 0,
		groupBuyTotalPrice:0,
      newPrice: '',
      index: index,
      group_buy_number: '',
    })
  },

  //关闭团购修改价格弹框
  closeGroupBuyModifyPrice: function () {
    this.setData({
      groupBuyModifyPriceCol: true
    })
  },

  //团购分享数量输入
  groupBuyNumberInput: function (e) {
    var reg = /^[1-9]\d*$/;
    var number = e.detail.value;
    if (!reg.test(number)) {
      number = ''
    }
    this.setData({
      group_buy_number: number,
    })
  },

  //团购确认修改价格
  groupBuyConfirm: function () {
    var that = this;
    var params = new Object()
    var newPrice = parseFloat(that.data.newPrice)
    var bottom_price = parseFloat(that.data.rawData.bottom_price)
    var original_price = parseFloat(that.data.rawData.original_price)
    if (that.data.group_buy_number == '' || that.data.group_buy_number==undefined){
      util.showStatus("请输入团购数量");
      return false;
    }

    if (isNaN(newPrice)) {
      newPrice = 0
    }
    if (newPrice == '') {
      params.share_price = that.data.rawData.current_price;
    } else {
      if (newPrice < bottom_price) {
        util.showStatus("价格不得低于" + bottom_price);
        that.setData({
          newPrice: '',
          preferentialPrice: 0
        })
        return false
      }
      if (newPrice > original_price) {
        that.setData({
          newPrice: '',
          preferentialPrice: 0
        })
        util.showStatus("价格不得高于" + original_price);
        return false
      }
      params.share_price = that.data.newPrice;
    }


    params.sku_code = that.data.rawData.sku_code;
    params.type = 2;
    params.num = that.data.group_buy_number;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'goods/shareSub',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          util.showStatus("修改成功")
          that.setData({
            share: 2,
            group_share_id: res.data.data.share_id,
            group_share_img: res.data.data.code_img
          })
        } else {
          util.showStatus(res.data.message)
        }
      },
      fail: function (fail) {
        util.showErrorPath("../../../", "获取失败，请检查网络");
      }
    })
  },

})